package com.example.mybatisdemo;

import java.sql.*;

public class JDBCDemo {
    // JDBC 驱动程序和数据库 URL
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/test";

    // 数据库用户和密码
    static final String USER = "root";
    static final String PASS = "123456";

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 注册 JDBC 驱动程序
        Class.forName(JDBC_DRIVER);

        // 建立连接
        System.out.println("Connecting to database...");
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

        // 创建并执行查询
        String sql;
        sql = "SELECT id, name FROM users";
        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery(sql);

        // 处理结果集
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");

            // 显示结果
            System.out.print("ID: " + id);
            System.out.print(", Name: " + name);
            System.out.println();
        }

        // 关闭资源
        rs.close();
        stmt.close();
        conn.close();
    }
}
